<template>
  <div class="grade-list">
    <a-card title="成绩列表">
      <template #extra>
        <a-space>
          <a-button @click="$router.push('/grades/import')">批量导入</a-button>
          <a-button type="primary" @click="showCreateModal">录入成绩</a-button>
        </a-space>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="学号">
          <a-input v-model:value="searchForm.student_id" placeholder="请输入学号" style="width: 150px" />
        </a-form-item>
        <a-form-item label="姓名">
          <a-input v-model:value="searchForm.student_name" placeholder="请输入姓名" style="width: 120px" />
        </a-form-item>
        <a-form-item label="专业">
          <a-input v-model:value="searchForm.major" placeholder="请输入专业" style="width: 120px" />
        </a-form-item>
        <a-form-item label="班级">
          <a-input v-model:value="searchForm.class_name" placeholder="请输入班级" style="width: 120px" />
        </a-form-item>
        <a-form-item label="学年">
          <a-select v-model:value="searchForm.time" placeholder="请选择" style="width: 100px" allow-clear>
            <a-select-option :value="2025">2025</a-select-option>
            <a-select-option :value="2024">2024</a-select-option>
            <a-select-option :value="2023">2023</a-select-option>
            <a-select-option :value="2022">2022</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="课程">
          <a-input v-model:value="searchForm.course_name" placeholder="课程名称" style="width: 150px" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
            <a-button @click="$router.push('/grades/statistics')">成绩统计</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'grade'">
            <a-tag :color="Number(record.grade) >= 60 ? 'green' : 'red'">
              {{ record.grade }}
            </a-tag>
          </template>
          <template v-if="column.key === 'created_at'">
            {{ record.created_at ? new Date(record.created_at).toLocaleString() : '-' }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="showEditModal(record)">编辑</a>
              <a style="color: #ff4d4f" @click="handleDelete(record.id)">删除</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 录入/编辑成绩弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="600px"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="学生ID" required>
          <a-input-number
            v-model:value="formData.student_id"
            placeholder="请输入学生ID"
            style="width: 100%"
            :disabled="!!currentRecord"
          />
        </a-form-item>
        <a-form-item label="选择课程" required>
          <a-select 
            v-model:value="selectedCourseId" 
            placeholder="请选择课程" 
            style="width: 100%"
            show-search
            :filter-option="filterCourse"
            @change="handleCourseChange"
          >
            <a-select-option 
              v-for="course in courses" 
              :key="course.id" 
              :value="course.id"
            >
              {{ course.course_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="成绩" required>
          <a-input v-model:value="formData.grade" placeholder="请输入成绩" />
        </a-form-item>
        <a-form-item label="学年" required>
          <a-select v-model:value="formData.time" placeholder="请选择学年" style="width: 100%">
            <a-select-option :value="2024">2024</a-select-option>
            <a-select-option :value="2023">2023</a-select-option>
            <a-select-option :value="2022">2022</a-select-option>
            <a-select-option :value="2021">2021</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { gradeAPI } from '@/api/grade'
import type { GradeDetail } from '@/api/grade'
import { courseAPI } from '@/api/system'
import type { Course } from '@/api/system'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const dataSource = ref<GradeDetail[]>([])
const modalVisible = ref(false)
const modalTitle = ref('录入成绩')
const currentRecord = ref<GradeDetail | null>(null)
const courses = ref<Course[]>([])
const selectedCourseId = ref<number | undefined>(undefined)

const formData = reactive({
  student_id: undefined as number | undefined,
  course_no: '',
  course_name: '',
  grade: '',
  time: undefined as number | undefined
})

const searchForm = reactive({
  student_id: '',
  student_name: '',
  major: '',
  class_name: '',
  time: undefined as number | undefined,
  course_name: ''
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: '学号', dataIndex: 'student_id', key: 'student_id', width: 120 },
  { title: '姓名', dataIndex: 'student_name', key: 'student_name', width: 100 },
  { title: '专业', dataIndex: 'major_name', key: 'major_name', width: 120 },
  { title: '班级', dataIndex: 'class_name', key: 'class_name', width: 100 },
  { title: '课程名称', dataIndex: 'course_name', key: 'course_name' },
  { title: '成绩', key: 'grade', width: 80 },
  { title: '学年', dataIndex: 'time', key: 'time', width: 80 },
  { title: '操作', key: 'action', width: 120 }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载课程列表
const loadCourses = async () => {
  try {
    const res = await courseAPI.getList({} as any)
    courses.value = res.data.results
  } catch (error: any) {
    message.error('加载课程列表失败: ' + (error.response?.data?.message || error.message))
  }
}

// 课程搜索过滤
const filterCourse = (input: string, option: any) => {
  const course = courses.value.find(c => c.id === option.value)
  return course?.course_name?.toLowerCase().includes(input.toLowerCase()) || false
}

// 课程选择变化
const handleCourseChange = (courseId: number) => {
  const course = courses.value.find(c => c.id === courseId)
  if (course) {
    formData.course_no = course.id.toString()
    formData.course_name = course.course_name
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await gradeAPI.getGradeList({
      page: pagination.value.current,
      page_size: pagination.value.pageSize,
      student_id: searchForm.student_id || undefined,
      student_name: searchForm.student_name || undefined,
      major: searchForm.major || undefined,
      class_name: searchForm.class_name || undefined,
      time: searchForm.time,
      course_name: searchForm.course_name || undefined
    })
    dataSource.value = res.data.results
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.student_id = ''
  searchForm.student_name = ''
  searchForm.major = ''
  searchForm.class_name = ''
  searchForm.time = undefined
  searchForm.course_name = ''
  pagination.value.current = 1
  loadData()
}

// 显示新建弹窗
const showCreateModal = () => {
  modalTitle.value = '录入成绩'
  currentRecord.value = null
  formData.student_id = undefined
  formData.course_no = ''
  formData.course_name = ''
  formData.grade = ''
  formData.time = undefined
  selectedCourseId.value = undefined
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: GradeDetail) => {
  modalTitle.value = '编辑成绩'
  currentRecord.value = record
  formData.student_id = record.student_id
  formData.course_no = record.course_no?.toString() || ''
  formData.course_name = record.course_name
  formData.grade = record.grade
  formData.time = record.time
  
  // 根据课程名称查找对应的课程id
  const course = courses.value.find(c => c.course_name === record.course_name)
  selectedCourseId.value = course?.id
  
  modalVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  // 验证必填项
  if (!formData.student_id || !formData.course_name || !formData.grade || !formData.time) {
    message.error('请填写所有必填项')
    return
  }

  try {
    const submitData = {
      student_id: formData.student_id,
      course_no: formData.course_no ? Number(formData.course_no) : undefined,
      course_name: formData.course_name,
      grade: formData.grade,
      time: formData.time
    }

    if (currentRecord.value) {
      // 编辑
      await gradeAPI.updateGrade(currentRecord.value.id, submitData)
      message.success('更新成功')
    } else {
      // 新建
      await gradeAPI.createGrade(submitData)
      message.success('录入成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error: any) {
    message.error('操作失败: ' + (error.response?.data?.message || error.message))
  }
}

// 取消
const handleCancel = () => {
  modalVisible.value = false
}

// 删除
const handleDelete = (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条成绩记录吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await gradeAPI.deleteGrade(id)
        message.success('删除成功')
        loadData()
      } catch (error: any) {
        message.error('删除失败: ' + (error.response?.data?.message || error.message))
      }
    }
  })
}

onMounted(() => {
  loadCourses()
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
